package com.my.security;

import com.alibaba.druid.util.StringUtils;
import com.my.sys.model.SysRole;
import com.my.sys.model.SysUser;
import com.my.sys.service.SysUserService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by 80002023 on 2016/5/3.
 */
@Service
public class AuthRealm extends AuthorizingRealm {

    private final Logger logger = LogManager.getLogger(getClass());

    @Autowired
    private SysUserService sysUserService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = (String) principalCollection.fromRealm(getName()).iterator().next();
        logger.info("{}[用户]授权认证", username);
        SysUser user = sysUserService.findByUsername(username);
        if (user != null) {
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            for (SysRole role : user.getRoles()) {
                info.addRole(role.getKey());
                info.addStringPermissions(role.getStringPermissions());
            }
            return info;
        }
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        if (!StringUtils.isEmpty(username)) {

            logger.info("{}[用户]登录认证", username);
            int status = sysUserService.login(token.getUsername(), String.valueOf(token.getPassword()));

            logger.info("[用户]登录状态:{} ", status);
            if (status == 1) {
                SysUser user = sysUserService.findByUsername(username);
                return new SimpleAuthenticationInfo(user.getUsername(), token.getPassword(), getName());
            } else if (status == 0) {
                throw new UnknownAccountException();
            } else if (status == -1) {
                throw new IncorrectCredentialsException();
            }
            //throw new DisabledAccountException();
        }
        return null;
    }
}
